import { thyReq, initImplements, UITypes, thyCookie, thyUrl } from '@thyiad/util';
import { LOGIN_COOKIE_KEY, REQUEST_HEADER_TOKEN_NAME } from '../constants';
import { showToast, showLoadingToast, showDialog, showSuccessToast, showFailToast, showConfirmDialog } from 'vant';

/**
 * 顶部加载中提示，vant需要用clearToast
 * @param msg 提示内容
 */
const msgLoading = (msg: string) => {
    return showLoadingToast({
        message: msg,
        duration: 0,
    });
};

/**
 * toast消息
 * @param msg 需要toast的消息内容
 * @param type 类型：success, warning, error, info，默认success
 */
const toast = (msg: string, type: UITypes = UITypes.success) => {
    switch (type) {
        case UITypes.success:
            showSuccessToast(msg);
            break;
        case UITypes.error:
            showFailToast(msg);
            break;
        default:
            showToast(msg);
            break;
    }
};

/**
 * alert 消息框
 * @param msg alert 的 消息内容
 * @param type 类型：info, success, warning, error，默认 info
 * @param content 弹窗内容
 * @param cb 确认回调
 */
const alert = (msg: string, type: UITypes = UITypes.success, content = '', cb?: () => void) => {
    showDialog({
        title: msg,
        message: content,
    }).then(cb);
};

/**
 * 确认弹窗
 * @param msg 提示消息
 * @param ok 确认回调
 * @param cancel 取消回调
 */
const confirm = (msg: string, ok?: () => void, cancel?: () => void, content?: string) => {
    showConfirmDialog({
        title: msg,
        message: content,
    })
        .then(ok)
        .catch(cancel);
};

export const logout = () => {
    thyCookie.remove(LOGIN_COOKIE_KEY, { domain: thyUrl.getBaseHost() });
    const idx = window.location.href.indexOf('#');
    const base = window.location.href.slice(0, idx);
    window.location.href = `${base}#/user/login`;
};

export const initThyiadUtils = () => {
    initImplements({
        ui: {
            msgLoading,
            toast,
            alert,
            confirm,
        },
        req: {
            loginCookeyKey: LOGIN_COOKIE_KEY,
            tokenHeaderName: REQUEST_HEADER_TOKEN_NAME,
            ajaxStatus: {
                success: 200,
                error: 1102,
                expired: 1101,
            },
            ajaxData: {
                code: 'returnCode',
                msg: 'returnMsg',
                data: 'result',
            },
            logout,
        },
    });
};
